﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include "quiwidget.h"

hid_device *g_device;
bool g_isRecv = true;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->statusLab->setStyleSheet("background:#ff0000;");
    ReadUSB *worker = new ReadUSB;
    worker->moveToThread(&m_thread);
    connect(&m_thread, &QThread::finished, worker, &QObject::deleteLater);
    connect(this, &MainWindow::operate, worker, &ReadUSB::readData);
    connect(worker, &ReadUSB::resultReady, this, &MainWindow::handleResults);
    m_thread.start();
}

MainWindow::~MainWindow()
{
    g_isRecv = false;

    m_thread.quit();
    m_thread.wait();

    delete ui;
    if (m_handle) {
        hid_close(m_handle);
        m_handle = nullptr;
    }
    hid_exit();
}

void MainWindow::on_openBtn_clicked()
{
    if (m_handle) {
        hid_close(m_handle);
        m_handle = nullptr;
        m_isOpen = false;
        ui->statusLab->setText("OFF");
        ui->openBtn->setText("打开USB");
        ui->statusLab->setStyleSheet("background:#ff0000;");
    } else {
        QString pid = ui->pidBox->currentText();
        QString vid = ui->vidBox->currentText();
        if (pid == "" || vid == "") {
            return;
        }
        bool ok = false;
        ushort upid = pid.toUShort(&ok,16);
        ushort uvid = vid.toUShort(&ok,16);
        //        m_handle = hid_open(0x1234, 0xABCD, NULL);
        m_handle = hid_open(uvid, upid, NULL); //打开设备
        qDebug() << m_handle;
        if (m_handle) {
            g_device = m_handle;
            emit operate();
            m_isOpen = true;
            ui->statusLab->setText("ON");
            ui->openBtn->setText("关闭USB");
            ui->statusLab->setStyleSheet("background:#00ff00;");
        }
    }
}

/**
* @projectName   USB_HID
* @brief         发送数据，注意头部要多发一个字节，协议是这样定的
* @author        Sean
* @date          2021-08-04
* @Email         sean.qter@qq.com
*/
void MainWindow::on_sendBtn_clicked()
{
    if (m_handle == nullptr)    return;
    QString text = ui->sendEdit->toPlainText();
    if (text.isEmpty()) {
        ui->sendEdit->setFocus();
        return;
    }

    QByteArray buffer;
    if (ui->ckHexSend->isChecked()) {
        buffer = QUIHelper::hexStrToByteArray(text);
    } else {
        buffer = QUIHelper::asciiStrToByteArray(text);
    }
    int size = buffer.size();
    qDebug() << size;
    u_char * data = (uchar *)buffer.data();

    hid_write(m_handle, data, size);  //写数据

}

void MainWindow::on_clearSendBtn_clicked()
{
    ui->sendEdit->clear();
}

void MainWindow::on_clearRecvBtn_clicked()
{
    ui->recvEdit->clear();
}

void MainWindow::handleResults(const QByteArray &str)
{
    QString buffer;
    if (ui->ckHexRecv->isChecked()) {
        buffer = QUIHelper::byteArrayToHexStr(str);
    } else {
        buffer = QString::fromLocal8Bit(str);
    }
    ui->recvEdit->append(buffer);
}

void ReadUSB::readData()
{
    while (1) {
        if (!g_isRecv) break;
        u_char rbuf[64] = {0x00};
        int ret = -1;
        ret = hid_read_timeout(g_device, rbuf, 64, 100);//读数据
        QByteArray sbuf = "";
        if (ret > 0) {
            for (int i = 0; i != ret; i++) {
                sbuf += rbuf[i];
            }
            emit resultReady(sbuf);
            qDebug() << "sbuf:" << sbuf << "sizeof:" << sizeof(rbuf);
        }

        QUIHelper::msleep(1000);
    }
}
